package com.lsy.on_line.zaixian.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lsy.on_line.zaixian.utils.JWTUtils;
import com.lsy.on_line.zaixian.utils.JsonData;
import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import freemarker.template.utility.StringUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.crypto.interfaces.PBEKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 进入到controller之前的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            String accesToken = request.getHeader("token");
            if (accesToken == null) {
                request.getParameter("token");
            }
            if (StringUtils.isNoneBlank(accesToken)) {
                Claims claims = JWTUtils.claimsJWT(accesToken);
                if (claims == null) {
                    //返回false登录失败，提示请重新登录
                    sendJsonMessage(response, JsonData.buildError("登录过期,请重新登陆!"));
                    return false;
                }
                Integer id = (Integer) claims.get("id");
                String name = (String) claims.get("name");
                //设置属性值
                request.setAttribute("user_id", id);
                request.setAttribute("name", name);
                //登陆成功
                return true;
            }
        }catch (Exception e){}
        //登录失败
        return false;
}

    /**
     * 响应Json数据给前端 （如果检验失败需要返回给前端）
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response,Object obj){

        try {
            //对象映射器
            ObjectMapper objectMapper = new ObjectMapper();
            //设置内容格式类型
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            //以流的形式写入
            writer.print(objectMapper.writeValueAsString(obj));
            //关闭写流
            writer.close();
            //刷新
            response.flushBuffer();
        }catch (Exception e){}

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
